<?php

namespace App\Http\Controllers\Resource;

use Illuminate\Support\Facades\Log;

/**
 * 掌阅 数字资源
 *
 * 已提供 目录接口
 */
class ZyController extends CommonController
{
    public $rent_id = '101541';
    public $app_id = '6b5f4417';
    public $company_id = '101541';
    public $private_key = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKc/a4oZr2ykUM3D8zNC/LhcjeOjb4jk1IPMfFb7q2/IosuNTBXljLFPQxfIvtgbQTyQt5lleBcSnbbkKBu8ZcVWAWYGAPzn+P/CkcHbveWcaNvH1icgMUwVG17kVgrZq1UCzCO3jrFG/hQMB6SFsxODjJoV3wFqKJ/jB84dMInBAgMBAAECgYAlY4UsA1/3Pqidx2+IBzKuGGrT+AaIKPflWwJ1A6Aoxka2kKjwwDd6sAiEuakIcNddrdCNp2R4a/38E/dvc+egICpjDOwizz4ndRwNp3mUFI7xg4HZRwfr6vThORU4epenSX1Tw0TZPIaVp2V2bK4CSG4dv7x4mzCWg4o+BDgILQJBAODstD8T8IO9L+f7vwdmx0LGSHaj5QMYQURDGqJy/ajH1ySe2PbTxsb6H2XWP2rwQfwG1/3+jH8boE+LOQ5y0BcCQQC+WsIb7gyPRVKVc/o0t+2LicMiK2ma77gQlzF5bS9WPnoOZGpi7Fs7DUQHwuXB3gHnsCUiTfAXvm0u7r4TnYPnAkEA0N29+51OiWdTZz81g3ADtZRfkhxb++W4JeWShCv4NZVtycngfETon7mBEpZDydBV1e2dAXYxjY9f7L3CPBKN/QJAEZ/toRBlcU6F2vimDgOJpwXWX2+Nk57meALHvepyG5YlTvfVMduYhtsvlVhiVZTssDsK9SYqOMiU62eHieFnuQJBAITyUQJ7V6b+YgDj9yPYy48150LSDGwvDBbgS751eGVX+VsiDfZfdCcNOdACeJ4bIpNMgnFJ8qsBqf6L+Nq7LQo=';


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 租⼾全量书籍id获取接⼝（电⼦书&听书）
     */
    public function getBookIdAll()
    {
        $url = 'https://ir.zhangyue.com/nd_activity/out/company/v3/bookIds';
        $sign = $this->getSign(['companyId' => $this->company_id]);

        $result = request_url($url, json_encode(['companyId' => $this->company_id, 'sign' => $sign]), 10, true);
        $result = json_decode($result, true);
        if (!isset($result['code']) || $result['code'] !== 0 || empty($result['body']['bookFileurl'])) {
            Log::channel('zylog')->debug('资源获取失败');
            Log::channel('zylog')->debug($url);
            Log::channel('zylog')->debug($result);
            Log::channel('zylog')->debug('--------------------------------------------------------');
            return []; //没数据时，返回的false
        }
        $file_address = $result['body']['bookFileurl'];
        $data = file_get_contents($file_address); //获取所有数据
        if (empty($data)) {
            return [];
        }
        $data = json_decode($data, true);
        return array_column($data, 'bookIds', 'type');
    }



    /**
     * 书籍详情获取接⼝（电⼦书&听书）
     * @param companyId 企业id:企业⾝份在掌阅唯⼀id
     * @param bookIds 要查询的书籍id集合(不参与签名)
     * @param type "type=1 表⽰bookIds为电
            ⼦书id数组type=2 表⽰
            bookIds为有声书id数组"
            (不参与签名)
     */
    public function getBookDetail($book_ids, $type)
    {
        $url = 'https://ir.zhangyue.com/nd_activity/out/company/bookInfos';
        $sign = $this->getSign(['companyId' => $this->company_id]);

        $result = request_url($url, json_encode(['companyId' => $this->company_id, 'sign' => $sign, 'bookIds' => $book_ids, 'type' => $type]), 10, true);
        $result = json_decode($result, true);
        if (!isset($result['code']) || $result['code'] !== 0 || empty($result['body'])) {
            Log::channel('zylog')->debug('资源获取失败');
            Log::channel('zylog')->debug($url);
            Log::channel('zylog')->debug($result);
            Log::channel('zylog')->debug('--------------------------------------------------------');
            return []; //没数据时，返回的false
        }
        return  $result['body'];
    }

    /**
     *获取目录接口
     * @param type 1 电子书，2 有声书
     */
    public function getBookCatalogue($book_id, $type)
    {
        if ($type == 1) {
            $url = 'https://ir.zhangyue.com/nd_activity/out/company/bookChapters'; //获取电子书章节信息文件 （返回xml文件）
        } else {
            $url = 'https://ir.zhangyue.com/nd_activity/out/company/getCommonChaptersUrl'; //获取听书章节信息文件 （返回xml文件）
        }

        $sign = $this->getSign(['companyId' => $this->company_id, 'bookId' => $book_id]);
        $result = $this->curlPost($url, json_encode(['companyId' => $this->company_id, 'sign' => $sign, 'bookId' => $book_id]), 10, true);

        if (empty($result)) {
            Log::channel('zylog')->debug('资源获取失败');
            Log::channel('zylog')->debug($url);
            Log::channel('zylog')->debug($result);
            Log::channel('zylog')->debug('--------------------------------------------------------');
            return []; //没数据时，返回的false
        }
        $result = xmlstr_to_array($result);
        $data = [];
        foreach ($result['cls']['cp'] as $key => $val) {
            $data['data'][$key]['resource_business_id'] = 8;
            $data['data'][$key]['book_id'] = $book_id;
            $data['data'][$key]['sort'] = $val['id'];; //排序
            $data['data'][$key]['chapter_id'] = $val['id'];
            $data['data'][$key]['chapter_name'] = $val['cn'];
            $data['data'][$key]['link'] = $val['cdu'];
            $data['data'][$key]['wc'] = $val['wc'];
            $data['data'][$key]['csz'] = $val['csz'];
            $data['data'][$key]['cwc'] = $val['cwc'];
        }
        $data['total'] = $result['page']['totalRecord'];
        $data['per_page'] = $result['page']['totalPage'];
        $data['current_page'] = $result['page']['currentPage'];
        return  $data;
    }

    /**
     * 书籍阅读⻚(进⼊指定书籍的章节阅读⻚)
     * @param  user_id String 用户唯一标识
     * @param  book_id String 书籍ID
     * @param  chapter_id String 章节ID
     * @param  type 1 电子书，2 有声书
     */
    public function getReadPage($user_id, $book_id, $chapter_id, $type)
    {
        $timestamp = time();
        if ($type == 1) {
            $sign = $this->getH5Sign(['appId' => $this->app_id, 'rentId' => $this->rent_id, 'timestamp' => $timestamp, 'userId' => $user_id]);
            $url = 'https://s1.zhangyue.com/read?bid=' . $book_id . '&cid=' . $chapter_id . '&appId=' . $this->app_id . '&rentId=' . $this->rent_id . '&timestamp=' . $timestamp . '&userId=' . $user_id . '&sign=' . $sign;
        } else {
            $sign = $this->getH5Sign(['appId' => $this->app_id, 'rentId' => $this->rent_id, 'timestamp' => $timestamp, 'userId' => $user_id]);
            $url = 'https://s1.zhangyue.com/audio/ting?bookId=' . $book_id . '&chapterId=' . $chapter_id . '&appId=' . $this->app_id . '&rentId=' . $this->rent_id . '&timestamp=' . $timestamp . '&userId=' . $user_id . '&sign=' . $sign;
        }

        return $url;
    }

    /**
     * 获取签名
     * @param $data
     */
    public function getH5Sign($param = [])
    {
        $param = $this->arraySort($param);
        $params = http_build_query($param); //null 不参与拼接，但是 空字符串要参与拼接

        $params = substr(md5($params), 6, 18);
        $sign = substr(md5($params), 10, 16);
        return $sign;
    }


    /**
     * 获取签名
     * @param $data
     */
    public function getSign($param = [])
    {
        $param = $this->arraySort($param);
        $params = http_build_query($param); //null 不参与拼接，但是 空字符串要参与拼接

        $sign = $this->rsaEncrypt($params, $this->private_key);
        return $sign;
    }


    function rsaEncrypt(string $content, string $privateKey): string
    {
        try {
            // 将 Base64 编码的私钥转换为 PEM 格式
            $privateKeyPem = "-----BEGIN PRIVATE KEY-----\n" .
                chunk_split($privateKey, 64, "\n") .
                "-----END PRIVATE KEY-----";

            // 加载私钥
            $privateKeyResource = openssl_pkey_get_private($privateKeyPem);

            // 使用 SHA1WithRSA 算法进行签名
            openssl_sign($content, $signed, $privateKeyResource, OPENSSL_ALGO_SHA1);

            // 将签名结果进行 Base64 编码
            $base64Signed = base64_encode($signed);

            // 释放私钥资源
            openssl_free_key($privateKeyResource);

            return $base64Signed;
        } catch (\Exception $e) {
            // 重新抛出异常
            throw $e;
        }
    }


    /**
     * 字典序排序
     */
    public function arraySort(array $param)
    {
        ksort($param);
        reset($param);

        return $param;
    }

    /**
     *获取电子书、有声书 目录地址，服务器内部做了 302 跳转，需要跟踪地址
     */
    public function curlPost($url, $params)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将结果作为字符串返回，而不是直接输出
        curl_setopt($ch, CURLOPT_POST, true); // 启用POST请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // 设置POST字段为JSON格式
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 启用重定向跟随

        //获取授权失败增加 2021-06-18
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch); // 执行cURL请求并获取响应
        if (curl_errno($ch)) { // 检查是否有错误发生
            $error_msg = curl_error($ch);
            die('cURL error: ' . $error_msg);
        }
        curl_close($ch); // 关闭cURL会话
        return $response;
    }
}
